package com.zzxx.service.impl;

import com.zzxx.entity.*;
import com.zzxx.exceptions.LoginException;
import com.zzxx.mapper.*;
import com.zzxx.service.UserService;
import com.zzxx.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private TicketMapper ticketMapper;
    @Autowired(required = false)
    private HttpServletRequest request;
    @Autowired
    private TicketScheduleMapper ticketScheduleMapper;
    @Override
    public String send(String email) throws LoginException {
        String random = ""+Math.random();
        String substring = random.substring(random.length()-4);

        boolean flag = MailUtils.sendMail(email, substring, "账号验证码");
        if(flag==false){
         throw new LoginException("defeated");
        }
        return substring;
    }

    @Override
    public void register(User user) throws LoginException {
        String uuid= UUID.randomUUID().toString().replace("-", "");
        user.setId(uuid);
        user.setStatus(0);
        user.setMoney(0.0);
        try {
            int i = userMapper.insert(user);
            if(i==1){
                String text="请点击连接<a href='http://localhost:8080/user/active?id="+user.getId()+"'>激活</a>"
                        +"如果浏览器跳转不过去，可以在浏览器手动输入http://localhost:8080/user/active?id="+user.getId()+"即可激活账号";
                MailUtils.sendMail(user.getEmail(),text,"账号激活");
            }
        }catch (Exception e){
            throw new LoginException("注册失败,原因可能是：1、账号已存在，2、身份证号已存在，3、邮箱已存在");
        }

    }

    @Override
    public User findUser(String username, String password) throws LoginException {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(example);
        if(users.size()==0){
            throw new LoginException("账号或者密码错误");
        }
        User user = new User();
        user=users.get(0);
        if(user.getStatus()==0){
            throw new LoginException("账号未激活");
        }
        return user;
    }

    @Override
    public Boolean active(String id) {
        User user = new User();
        user.setId(id);
        user.setStatus(1);
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i==1;
    }

    @Override
    public User findById(String id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void loadPhoto(MultipartFile photoFile) throws Exception {
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        if(loginUser==null){
            throw new LoginException("noUser");
        }
        String parent = request.getServletContext().getRealPath("/user/");
        String photoName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
        String realPath=parent+photoName;
        String path = realPath.substring(realPath.indexOf("\\user"));
        loginUser.setSrc(path);
        userMapper.updateByPrimaryKeySelective(loginUser);
        request.getSession().setAttribute("loginUser",loginUser);
        File file = new File(parent,photoName);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        photoFile.transferTo(file);
    }

    @Override
    public void packageUserAndCoupons(UserAndCoupons uac, String tid) {
        String uid = uac.getLoginUser().getId();
        //查出ticket放进去
        Ticket ticket = ticketMapper.selectByPrimaryKey(tid);
        uac.setTicket(ticket);
        UserCouponExample ucexample = new UserCouponExample();
        ucexample.createCriteria().andUseridEqualTo(uid);
        List<UserCoupon> userCoupons = userCouponMapper.selectByExample(ucexample);
        userCoupons.forEach(n->{
            //如果被使用就跳过
            if (n.getStatus()==0){
                Coupon coupon = couponMapper.selectByPrimaryKey(n.getCouponid());
                //如果不是这个票的就跳过
                if (coupon.getTargetid().equals(tid)){
                    //计算剩余时间
                    int day = computedDay(n.getActivetime(), new Date());
                    int lastDay = coupon.getIndate() - day;
                    //如果lastDay<0代表过期，将它删除
                    if (lastDay<0){
                        userCouponMapper.deleteByPrimaryKey(coupon.getId());
                    }else{
                        //没过期就添加进去
                        uac.getCoupons().add(coupon);
                        uac.getLastDays().add(lastDay);
                        uac.getUcIds().add(n.getId());
                    }
                }
            }
        });
        TicketScheduleExample ticketScheduleExample = new TicketScheduleExample();
        TicketScheduleExample.Criteria criteria = ticketScheduleExample.createCriteria().andTicketidEqualTo(tid);
        List<TicketSchedule> ticketSchedules = ticketScheduleMapper.selectByExample(ticketScheduleExample);
        Iterator<TicketSchedule> iterator = ticketSchedules.iterator();
        while (iterator.hasNext()){
            TicketSchedule t=iterator.next();
            uac.getTicketSchedules().add(t);
            uac.getTsIds().add(t.getId());
        }
    }

    @Override
    public void updateMoney(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }


    //计算d2-d1为多少天
    public int computedDay(Date d1, Date d2){
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        cal1.setTime(d1);
        cal2.setTime(d2);

        //获取日期在一年(月、星期)中的第多少天
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);//第335天
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);//第365天

        //获取当前日期所在的年份
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);

        //如果两个日期的是在同一年，则只需要计算两个日期在一年的天数差；
        //不在同一年，还要加上相差年数对应的天数，闰年有366天

        if(year1 != year2) //不同年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0) //闰年
                {
                    timeDistance += 366;
                }
                else //不是闰年
                {
                    timeDistance += 365;
                }
            }
            System.out.println(timeDistance + (day2-day1));
            return timeDistance + (day2-day1);
        }
        else //同年
        {
            return day2-day1;
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 8; i++) {
            System.out.println(UUID.randomUUID().toString().replaceAll("-",""));
        }
    }
}
